package com.supermarket.manage.provider.ucenter.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.supermarket.manage.common.constant.RedisKeyConstant;
import com.supermarket.manage.common.constant.StatusConstant;
import com.supermarket.manage.common.dto.PageBean;
import com.supermarket.manage.common.dto.ucenter.request.AddUserParams;
import com.supermarket.manage.common.dto.ucenter.request.UserAddRoleParams;
import com.supermarket.manage.common.dto.ucenter.request.UserPageParams;
import com.supermarket.manage.common.pojo.MyUser;
import com.supermarket.manage.provider.api.ucenter.UserManageService;
import com.supermarket.manage.provider.ucenter.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Faxon
 * @version 1.0
 * @date 2020-02-28 18:22
 **/
@Service(version = "1.0.0")
public class UserManageServiceImpl implements UserManageService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public PageBean<MyUser> getUserPageList(UserPageParams params) {
        PageHelper.startPage(params.getPage(), params.getSize());
        Page<MyUser> page = userMapper.getUserPageList(params);
        return new PageBean<>(page.getPageNum(), page.getPageSize(), page.getResult(), page.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteUserById(Long userId, String buyerId) {
        MyUser user = new MyUser();
        user.setId(userId);
        user.setStatus(StatusConstant.DELETED);
        user.setUpdated(new Date());
        int i = userMapper.updateById(user);
        if (i == 1) {
            redisTemplate.opsForHash().delete(RedisKeyConstant.USER + buyerId, userId);
        }
        return i == 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addUser(AddUserParams params) {
        MyUser user = new MyUser();
        user.setUsername(params.getUsername());
        user.setPassword(params.getPassword());
        user.setStatus(StatusConstant.USE);
        user.setBuyerId(params.getBuyerId());
        user.setRoleId(params.getRoleId());
        user.setCreated(new Date());
        user.setUpdated(new Date());
        int insert = userMapper.insert(user);
        if (insert == 1) {
            user.setPassword(null);
            BoundHashOperations<String, Long, String> ops = redisTemplate.<Long, String>boundHashOps(RedisKeyConstant.USER + params.getBuyerId());
            if (ops.keys().size() > 0) {
                ops.put(user.getId(), JSON.toJSONString(user));
            } else {
                saveUsersToRedis(params.getBuyerId());
            }
        }
        return insert == 1;
    }

    @Override
    public Boolean assignRoleToUser(UserAddRoleParams params) {
        MyUser user = new MyUser();
        user.setId(params.getUserId());
        user.setRoleId(params.getRoleId());
        user.setUpdated(new Date());
        int i = userMapper.updateById(user);
        if (i == 1) {
            BoundHashOperations<String, Long, String> ops = redisTemplate.<Long, String>boundHashOps(RedisKeyConstant.USER + params.getBuyerId());
            String json = ops.get(params.getUserId());
            if (StringUtils.isBlank(json)) {
                saveUsersToRedis(params.getBuyerId());
            } else {
                MyUser myUser = JSON.parseObject(json, MyUser.class);
                user.setRoleId(params.getRoleId());
                user.setUpdated(new Date());
                ops.put(myUser.getId(), JSON.toJSONString(myUser));
            }
        }
        return i == 1;
    }

    @Override
    public List<MyUser> getUserList(UserPageParams params) {
        return userMapper.getUserList(params);
    }

    /**
     * 同步用户信息到redis
     *
     * @param buyerId
     */
    private void saveUsersToRedis(String buyerId) {
        BoundHashOperations<String, Long, String> ops = redisTemplate.<Long, String>boundHashOps(RedisKeyConstant.USER + buyerId);
        QueryWrapper<MyUser> wrapper = new QueryWrapper<>();
        wrapper.eq("buyer_id", buyerId).eq("status", StatusConstant.USE);
        List<MyUser> users = userMapper.selectList(wrapper);
        Map<Long, String> map = new HashMap<>(users.size());
        users.forEach(u -> {
            u.setPassword(null);
            map.put(u.getId(), JSON.toJSONString(u));
        });
        if (map != null && map.size() > 0) {
            ops.putAll(map);
        }
    }
}
